#include "declares.h"
#include "test.h"
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static pid_t pid;

pid_t start_test()
{
    switch (pid = fork())
    {
    case -1:
        return -1;
    case 0:
        break;
    default:
        return pid;
    }
    if (chdir(home_dir) != -1)
        DEBUG("%s: chdir: %s", __FUNCTION__, home_dir);
    if (chdir("src") != -1)
        DEBUG("%s: chdir: src", __FUNCTION__);

    setpgid(0, 0);
    DEBUG("%s pgid %d", __FILE__, getpgid(0));
    if (execl("/bin/bash", "bash", "-c", "./main", NULL) < 0)
    {
        DEBUG("start test failed");
        perror("execl");
        exit(EXIT_FAILURE);
    }
}

void close_test()
{
    DEBUG("test is running");
    DEBUG("kill test, pid is %d", pid);

    killpg(pid, SIGINT);

    DEBUG("waiting test exit");
    int code;
    waitpid(pid, &code, 0);

    DEBUG("test returned %d", code);
}